package com.rainbow.common.handler.error;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.rainbow.common.core.toolkit.MessageI18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author rainbow
 * sentinel流量控制自定义异常处理
 */
@Component
@Slf4j
public class SentinelErrorHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
        String resource= StringUtils.isEmpty(ex.getRule().getResource())?"":ex.getRule().getResource();
        log.error(String.format("sentinel降级资源名称%s", resource), ex);
        Map<String, Object> info = new LinkedHashMap<>();
        info.put("data",resource);
        info.put("code",500);
        if (ex instanceof FlowException) {
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"limit.param.error","Blocked by Sentinel (flow limiting)"));
        } else if (ex instanceof DegradeException) {
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"degrade.param.error","Blocked by Sentinel (degrade block)"));
        } else if (ex instanceof ParamFlowException) {
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"param.flow.error","Blocked by Sentinel (param flow block)"));
        } else if (ex instanceof SystemBlockException) {
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"system.param.error","Blocked by Sentinel (system block)"));
        } else if (ex instanceof AuthorityException) {
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"authority.param.error","Blocked by Sentinel (authority block)"));
        }else{
            info.put("msg", MessageI18nUtil.getMessage(request.getLocale(),"limit.param.error","Blocked by Sentinel (flow limiting)"));
        }
        response.setStatus(200);
        response.setHeader("content-type", "application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(info));

    }

}

